<template>
  <div class="upload-excel-container">
    <el-row class="mb-3">
      <el-col :span="6" :push="3" v-if="checkDataAllNum != 0" class="tx-right">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>查重详情</span>
          </div>

          <el-col :span="12">
            <el-row class="text item">
              <el-col :span="12">{{ '总数据' }}</el-col>
              <el-col :span="12">
                <el-tag size="mini">{{ checkDataAllNum }}</el-tag>
              </el-col>
            </el-row>
            <el-row class="text item">
              <el-col :span="12">{{ '非法数据' }}</el-col>
              <el-col :span="12">
                <el-tag size="mini" type="danger">{{ illegalRowNum }}</el-tag>
              </el-col>
            </el-row>
            <el-row class="text item">
              <el-col :span="12">{{ '重复数据' }}</el-col>
              <el-col :span="12">
                <el-tag size="mini" type="warning">{{ checkDataNum }}</el-tag>
              </el-col>
            </el-row>
            <el-row class="text item">
              <el-col :span="12">{{ '重复比例' }}</el-col>
              <el-col :span="12">
                <el-tag
                  size="mini"
                  type="info"
                >{{ ((checkDataNum / checkDataAllNum) * 100).toFixed(0) + "%" }}</el-tag>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="12" class="tx-center">
            <el-popover
              ref="popover1"
              placement="top-start"
              title="查重数据进度"
              width="200"
              trigger="hover"
              :content="checkDataNum + '/' + checkDataAllNum + ' (已查的重复数据/需查重总数据)'"
            ></el-popover>
            <el-progress
              v-popover:popover1
              v-if="checkPercentage != 100"
              type="circle"
              :percentage="checkPercentage"
            ></el-progress>
            <el-progress v-popover:popover1 v-else type="circle" :percentage="100" status="success"></el-progress>
          </el-col>
        </el-card>
      </el-col>
      <el-col :span="12" :push="checkDataAllNum != 0 ? 5 : 8" class="el-row--flex">
        <uploadExcel-component :on-success="handleSuccess" :before-upload="beforeUpload"></uploadExcel-component>
      </el-col>
    </el-row>
    <el-row v-if="checking" class="mb-3">
      <el-button type="warning" @click="cancelUpload">取消上传</el-button>
    </el-row>

    <vxe-grid
      ref="xGrid"
      border
      resizable
      keep-source
      height="580"
      :row-class-name="getRowClassName"
      :loading="loading"
      :columns="tableColumn"
      :data="tableData"
      :keyboard-config="keyConfig"
      :edit-config="{trigger: 'manual', mode: 'row', autoClear: false,showStatus: true, icon: 'fa fa-file-text-o'}"
      :edit-rules="validRules"
    >
      <template v-slot:operate="{ row }">
        <template v-if="$refs.xGrid.isActiveByRow(row)">
          <vxe-button
            icon="fa fa-save el-icon-document"
            status="primary"
            title="保存"
            circle
            @click="saveRowEvent(row)"
          />
        </template>
        <template>
          <vxe-button
            icon="fa fa-edit el-icon-edit-outline"
            title="编辑"
            circle
            @click="editRowEvent(row)"
          />
        </template>
        <vxe-button
          icon="fa fa-trash el-icon-delete"
          title="删除"
          circle
          @click="removeRowEvent(row)"
        />
        <!-- <vxe-button icon="fa fa-eye el-icon-edit-outline" title="查看" circle></vxe-button> -->
        <!-- <vxe-button icon="fa fa-gear el-icon-edit-outline" title="设置" circle></vxe-button> -->
      </template>
    </vxe-grid>

    <vxe-toolbar>
      <template v-slot:buttons>
        <el-button
          v-if="noError"
          type="primary"
          @click="uploadData"
        >
          上传到服务器<i class="el-icon-upload el-icon--right" />
        </el-button>
      </template>
    </vxe-toolbar>
  </div>
</template>

<script>
import UploadExcelComponent from "@/components/UploadExcel/index.vue";

export default {
  name: "UploadExcel",
  components: { UploadExcelComponent },
  data() {
    return {
      loading: false,
      // tablePage: {
      //   total: 0,
      //   currentPage: 1,
      //   pageSize: 10
      // },
      keyConfig: {
        isArrow: true,
        isDel: true,
        isEnter: true,
        isTab: true,
        isEdit: true
      },
      tableColumn: [
        { type: 'seq', width: 60 },
        { type: 'checkbox', width: 50 },
        { field: 'Id', title: 'Name', editRender: { name: 'input' } },
        { field: 'Title', title: 'Nickname', editRender: { name: 'input' } },
        // { field: 'Author', title: 'Sex', editRender: { name: '$select', options: [] } },
        { field: 'Author', title: 'Sex', editRender: { name: 'input' } },
        { field: 'Readings', title: 'Role', editRender: { name: 'input' } },
        { field: 'Date', title: 'Describe', showOverflow: true, editRender: { name: 'input' } },
        // { field: '_type', title: 'Type', showOverflow: true, editRender: { name: 'input' } },
        { title: '操作', width: 200, slots: { default: 'operate' } }
      ],
      tableData: [],
      tableHeader: [],
      noError: false,
      validConfig: {
        // autoPos: true,
        // maxWidth: 2,
      },
      
      rowStatus: [],
      validRules: {
        Id: [
          { required: true, message: 'app.body.valid.rName' },
          // { min: 5, max: 10, message: '文件名长度在 3 到 50 个字符' }
        ]
      }
    };
  },
  created() {
    debugger
  },
  methods: {
    beforeUpload(file) {
      debugger
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (isLt1M) {
        return true;
      }

      this.$message({
        message: "Please do not upload files larger than 1m in size.",
        type: "warning",
      });
      return false;
    },
    handleSuccess({ results, header }) {
      
      this.fullValidEvent(results)
      this.tableData = results;
      this.tableHeader = header;
    },
    editRowEvent (row) {
      this.$refs.xGrid.setActiveRow(row)
    },
    saveRowEvent (row) {
      debugger
      this.fullValidEvent(this.tableData)
      this.$refs.xGrid.clearActived().then(() => {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.$message({
            message: '保存成功！',
            type: 'success'
          });
        }, 300)
      })
    },
    removeRowEvent (row) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$refs.xGrid.remove(row)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
      });
    },
    fullValidEvent (results) {
      results.forEach(item => item._type = 1)
      this.$refs.xGrid.fullValidate(results, (errMap) => {
        if (errMap) {
          let msgList = []
          Object.values(errMap).forEach(errList => {
            errList.forEach(params => {
              let { rowIndex, column, rules } = params
              rules.forEach(rule => {
                results[rowIndex]._message = `${column.title} 校验错误：${rule.message} \n`
                results[rowIndex]._type = 0
                // msgList.push(`第 ${rowIndex + 1} 行 ${column.title} 校验错误：${rule.message} \n`)
              })
            })
          })

          //排序
          results.sort((a, b) => a._type - b._type)

          results.filter(item => item._type == 0).forEach((item, index) => msgList.push(`第 ${index + 1} 行 ${item._message}`))

          this.$notify({
            dangerouslyUseHTMLString: true,
            type: "error",
            duration: 0,
            title: '错误信息提示',
            message:  
                      `<div class="red" style="max-height: 400px;overflow: auto;">
                        ${
                          msgList.map(msg => {
                            return `<div>${ msg }</div>`
                          })
                        }
                      </div>`
          });
        } else {
          this.$message.success(`校验成功！`);
          this.noError = true
        }
      })
    },
    getRowClassName({row, rowIndex, $rowIndex, column, columnIndex, $columnIndex}) {
      if(row._type == 0) {
        return 'error-row'
      } else if(row._type == 1) {
        return 'warning-row'
      }
    },
    beforeSubmit() {
      
    },
    async uploadData() {
      const res = await this.$http.post()
    },
  },
};
</script>

<style lang="css">

  .warning-row {
    background: oldlace!important;
  }

  .success-row {
    background: #f0f9eb!important;
  }

  .error-row {
    background: #f3c8c8!important;
  }

  .mb-3 {
    margin-bottom: 30px;
  }
</style>
